import React from 'react';
import { startOfMonth, endOfMonth, eachDayOfInterval, format, isSameMonth, isSameDay } from 'date-fns';
import { CalendarDay } from '../types';
import { getDayStatus } from '../utils/todoUtils';
import { getLunarDate, getFortune } from '../utils/lunarCalendar';

interface CalendarProps {
  currentDate: Date;
  selectedDate: Date;
  calendarData: Record<string, CalendarDay>;
  onSelectDate: (date: Date) => void;
}

export function Calendar({ currentDate, selectedDate, calendarData, onSelectDate }: CalendarProps) {
  const monthStart = startOfMonth(currentDate);
  const monthEnd = endOfMonth(currentDate);
  const days = eachDayOfInterval({ start: monthStart, end: monthEnd });

  const getBackgroundColor = (date: Date) => {
    const dateStr = format(date, 'yyyy-MM-dd');
    const dayData = calendarData[dateStr];
    
    if (!dayData?.todos.length) return 'bg-white';
    return getDayStatus(dayData.todos);
  };

  const getDayInfo = (day: Date) => {
    const dateStr = format(day, 'yyyy-MM-dd');
    const dayData = calendarData[dateStr];
    
    return {
      lunar: dayData?.dayInfo.lunar || getLunarDate(day),
      fortune: dayData?.dayInfo.fortune || getFortune(day)
    };
  };

  return (
    <div className="bg-white rounded-lg shadow p-4">
      <div className="grid grid-cols-7 gap-1">
        {['周日', '周一', '周二', '周三', '周四', '周五', '周六'].map(day => (
          <div key={day} className="text-center font-semibold p-2">
            {day}
          </div>
        ))}
        
        {days.map((day, idx) => {
          const dateStr = format(day, 'yyyy-MM-dd');
          const dayData = calendarData[dateStr];
          const dayInfo = getDayInfo(day);
          
          return (
            <div
              key={idx}
              onClick={() => onSelectDate(day)}
              className={`
                min-h-[100px] p-2 border rounded-lg cursor-pointer transition-colors
                ${getBackgroundColor(day)}
                ${isSameDay(day, selectedDate) ? 'ring-2 ring-blue-500' : ''}
                ${!isSameMonth(day, currentDate) ? 'opacity-50' : ''}
              `}
            >
              <div className="flex flex-col h-full">
                <div className="text-right mb-1">{format(day, 'd')}</div>
                <div className="text-xs text-gray-600">
                  <div>{dayInfo.lunar}</div>
                  <div className="text-purple-600">{dayInfo.fortune}</div>
                </div>
                {dayData?.todos && dayData.todos.length > 0 && (
                  <div className="text-xs mt-1 text-gray-500">
                    {dayData.todos.length} 任务
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}